<?php

class Admin_TaoBaoItemsController extends Zend_Controller_Action
{
    public function init()
    {
    	$this->view->headScript()->appendFile($this->view->baseUrl().'/js/jquery-1.8.1.min.js');
        /* Initialize action controller here */
    	include 'top/TopClient.php';
        include 'top/RequestCheckUtil.php';
        include 'top/request/UmpPromotionGetRequest.php';
        include 'top/request/TaobaokeItemsDetailGetRequest.php';
        include 'top/request/ItemGetRequest.php';
        
    }

    public function indexAction()
    {
        // action body
        //$test=new Txy_Util_TaobaoItem();
        //$test->updateTaobaoItems('18074100912');
        echo "start";
    	@set_time_limit(3600);
        if(function_exists('ini_set'))
        {
            ini_set('max_execution_time',3600);
            ini_set("memory_limit","256M");
        }
        $db_taobaoitem=new Application_Model_DbTable_TaobaoItems();
        $taobalitemlist=$db_taobaoitem->fetchAll();
        $db_pricelist=new Application_Model_DbTable_Pricelist();
        $db_pricemark=new Application_Model_DbTable_Pricemark();
        $i=0;
        $datalist=Array();
        $datamark=Array();
        foreach ($taobalitemlist as $taobaoitem){
        	$price=0;
        	if(null==$taobaoitem['promotion_price']||""==$taobaoitem['promotion_price']){
        		$price=$taobaoitem['price'];
        	}else{
        		$price=$taobaoitem['promotion_price'];
        	}
        	
        	$datalist['price']=$price;
        	$datamark['min_price']=$price;
        	$datamark['max_price']=$price;
        	$datalist['numiid']=$taobaoitem['num_iid'];
        	$datamark['numiid']=$taobaoitem['num_iid'];
        	$db_pricelist->addNew($datalist);
        	$db_pricemark->addNew($datamark);
        	$i++;
        	echo $i.":".$taobaoitem['num_iid']."<br/>";
        }

    }

    public function updateTempItemsAction()
    {
        // action body
        @set_time_limit(3600);
        if(function_exists('ini_set'))
        {
            ini_set('max_execution_time',3600);
            ini_set("memory_limit","256M");
        }
        include 'top/request/TaobaokeItemsGetRequest.php';
        $db_temptaobaoitem=new Application_Model_DbTable_Temptaobaoitems();
        $c = new TopClient;
        $c->appkey = '12532098';
        $c->secretKey = 'c22aee3f68fe4acc9015a1e9dba1cd16';
        $req = new TaobaokeItemsGetRequest;
        $req->setFields("num_iid,title,nick,pic_url,price,click_url,commission,commission_rate,commission_num,commission_volume,shop_click_url,seller_credit_score,item_location,volume");
        $req->setNick("淘岫玉");
        $req->setCid(50013957);
        $req->setSort(" commissionVolume_desc");
        $req->setPageSize(40);
                		
        for($pageNo=1;$pageNo<=100;$pageNo++){
           $req->setPageNo($pageNo);
           $resp = $c->execute($req);
           foreach ($resp->taobaoke_items->taobaoke_item as $taobaoe_item) {
               $db_temptaobaoitem->addNewTempTaobaoItems($taobaoe_item);
           }
    	}
    }
    
    public function updateItemPromotionAction(){
    	@set_time_limit(3600);
        if(function_exists('ini_set'))
        {
            ini_set('max_execution_time',3600);
            ini_set("memory_limit","256M");
        }
    	
		$db_taobaoitem=new Application_Model_DbTable_TaobaoItems();
		$items=$db_taobaoitem->getNeedUpdatePromotionItems(50);
		$util=new Txy_Util_TaobaoItem();
		ob_end_clean();
		echo count($items)."<br/>";
		foreach ($items as $item){
			$util->updateUmp($item['num_iid']);
			print str_repeat("  ", 4096);
			ob_flush();
            flush();
			sleep(1);//延时一会儿防止查询过快,api被阻塞;
		}
		if(count($items)>0){
		    $this->view->headMeta()->appendHttpEquiv('refresh','10');
		}
    }
    /**
     * 更新商品全部信息
     * Enter description here ...
     */
    public function updateTaobaoItemsStatusAction(){
  		@set_time_limit(3600);
        if(function_exists('ini_set'))
        {
            ini_set('max_execution_time',3600);
            ini_set("memory_limit","256M");
        }
    	
		$db_taobaoitem=new Application_Model_DbTable_TaobaoItems();
		$items=$db_taobaoitem->getNeedUpdatePromotionItems(100);
		echo count($items)."<br/>";
		
		$util=new Txy_Util_TaobaoItem();
		$numiids=array();
		foreach ($items as $item){
			$numiids[]=$item['num_iid'];
		}
		$str=implode(",", $numiids);
		$util->updateTaobaoItems($str);
    }
    
    private function updateStatus($tenItemsArr){
    	include_once 'TopSdk.php';
    	$numiidsArray=array();
    	foreach ($tenItemsArr as $item){
    		$numiidsArray[]=$item['num_iid'];
    	}
    	$db_taobaoitems=new Application_Model_DbTable_TaobaoItems();
    	$numiidsstr=implode(",", $numiidsArray);
    	$c = new TopClient;
        $c->appkey = '12532098';
        $c->secretKey = 'c22aee3f68fe4acc9015a1e9dba1cd16';
    	$req_item = new TaobaokeItemsDetailGetRequest;
    	$req_item2 = new ItemGetRequest;
    	$req_item2->setFields("num_iid");
    	$req_item->setFields("num_iid");
		$req_item->setNick("淘岫玉");
		$req_item->setNumIids($numiidsstr);
		$resp_item = $c->execute($req_item);
		if(isset($resp_item->taobaoke_item_details)){
			$resultArray=array();
			foreach($resp_item->taobaoke_item_details->taobaoke_item_detail as $item){
				$resultArray[]=(String)$item->item->num_iid;
			}
			foreach($tenItemsArr as $item){
				$item['change_flag']=0;
				if(in_array($item['num_iid'], $resultArray)){
					if($item['is_taobaoke']==0){
						$item['is_taobaoke']=1;
						$item['change_flag']=1;
					}
					if($item['is_onsale']>1){
						$item['is_onsale']=1;
						$item['change_flag']=1;
					}
					//continue;
				}else{
					if($item['is_taobaoke']==1){
						$item['is_taobaoke']=0;
						$item['change_flag']=1;
					}
					$req_item2->setNumIid($item['num_iid']);
					$resp_items2 = $c->execute($req_item2);
					if(isset($resp_items2->item)){
						if($item['is_onsale']>1){
							$item['is_onsale']=1;
							$item['change_flag']=1;
						}
					}else{
						if($item['is_onsale']!=0){
							$item['is_onsale']=$item['is_onsale']+1;
							$item['change_flag']=1;
						}
					}
				}
				if(1==$item['change_flag']){
					unset($item['change_flag']);
					$item['update_time']=new Zend_Db_Expr('now()');
					$db_taobaoitems->updateTaobaoItems($item, $item['num_iid']);
				}
			}
		}
    }

    public function listTempItemsAction()
    {
        // action body
		//$this->
		$config=new Zend_Config_Ini(APPLICATION_PATH."/configs/application.ini",'production');
		$db = Zend_Db::factory($config->resources->db);
		//$adapter = new Zend_Paginator_Adapter_DbSelect($db->select()->from('txy_temp_taobao')->where('item_status=2'));
		$adapter=new Txy_Extends_TempTaobaoPageinator($db->select()->from('txy_temp_taobao')->where('item_status=2'));
		$paginator = new Zend_Paginator($adapter);
		$paginator->setCurrentPageNumber($this->_getParam('page'));
		$this->view->paginator = $paginator;
    }
    
    public function listItemsAction(){
        $checkedLevel0=$this->getRequest()->getParam("level0");
        $checkedLevel1=$this->getRequest()->getParam("level1");
        $checkedLevel2=$this->getRequest()->getParam("level2");
        $checkedLevel3=$this->getRequest()->getParam("level3");
        $checkedLevel4=$this->getRequest()->getParam("level4");
        $charactereSession = new Zend_Session_Namespace('character');
        if(null!=$checkedLevel0){
            $charactereSession->level0=$checkedLevel0;
        }
        if(null!=$checkedLevel1){
            $charactereSession->level1=$checkedLevel1;
        }
        if(null!=$checkedLevel2){
            $charactereSession->level2=$checkedLevel2;
        }
        if(null!=$checkedLevel3){
            $charactereSession->level3=$checkedLevel3;
        }
        if(null!=$checkedLevel4){
            $charactereSession->level4=$checkedLevel4;
        }
    	$config=new Zend_Config_Ini(APPLICATION_PATH."/configs/application.ini",'production');
		$db = Zend_Db::factory($config->resources->db);
        
        $selecterLevel0=$db->select()->from('txy_item_characters',array('name'))->where('level=0');
        $res0=$db->fetchAll($selecterLevel0);
        $this->view->level0=$res0;
        $this->view->checkLevel0=$charactereSession->level0;
        
        $selecterLevel1=$db->select()->from('txy_item_characters',array('name'))->where('level=1');
        $res1=$db->fetchAll($selecterLevel1);
        $this->view->level1=$res1;
        $this->view->checkLevel1=$charactereSession->level1;
        
        $selecterLevel2=$db->select()->from('txy_item_characters',array('name'))->where('level=2');
        $res2=$db->fetchAll($selecterLevel2);
        $this->view->level2=$res2;
        $this->view->checkLevel2=$charactereSession->level2;
        
        $selecterLevel3=$db->select()->from('txy_item_characters',array('name'))->where('level=3');
        $res3=$db->fetchAll($selecterLevel3);
        $this->view->level3=$res3;
        $this->view->checkLevel3=$charactereSession->level3;
        
        $selecterLevel4=$db->select()->from('txy_item_characters',array('name'))->where('level=4');
        $res4=$db->fetchAll($selecterLevel4);
        $this->view->level4=$res4;
		$this->view->checkLevel4=$charactereSession->level4;
		
		$where="1";
		if(null!=$charactereSession->level0){
            $inLevel0=implode(',', $charactereSession->level0);
            $inLevel0=Txy_Util_Character::getSqlStr($inLevel0);
            $where.=" and level0 in(".$inLevel0.")";
        }
        if(null!=$charactereSession->level1){
            $inLevel1=implode(',', $charactereSession->level1);
            $inLevel1=Txy_Util_Character::getSqlStr($inLevel1);
            $where.=" and level1 in(".$inLevel1.")";
        }
        if(null!=$charactereSession->level2){
            $inLevel2=implode(',', $charactereSession->level2);
            $inLevel2=Txy_Util_Character::getSqlStr($inLevel2);
            $where.=" and level2 in(".$inLevel2.")";
        }
        if(null!=$charactereSession->level3){
            $inLevel3=implode(',', $charactereSession->level3);
            $inLevel3=Txy_Util_Character::getSqlStr($inLevel3);
            $where.=" and level3 in(".$inLevel3.")";
        }
        if(null!=$charactereSession->level4){
            $inLevel4=implode(',', $charactereSession->level4);
            $inLevel4=Txy_Util_Character::getSqlStr($inLevel4);
            $where.=" and level4 in(".$inLevel4.")";
        }
		echo $where;
		
		
		$adapter=new Zend_Paginator_Adapter_DbSelect($db->select()->from('txy_items_join_character')->where($where));
		$paginator = new Zend_Paginator($adapter);
		$paginator->setCurrentPageNumber($this->_getParam('page'));
		$this->view->paginator = $paginator;
    }
    
    public function shareItemsApproveAction(){
    	$db_share=new Application_Model_DbTable_Share();
    	$shareList=$db_share->getUncheckedItemsList();
    	$pinyin= new Txy_Util_PinYin();
    	foreach ($shareList as &$share){
    		$share['url_spell']=$pinyin->getPinYin(mb_convert_encoding($share['title'],'gbk','utf-8'));
    	}
    	
    	$paginator=new Zend_Paginator(new Zend_Paginator_Adapter_Array($shareList));
    	//$paginator=Zend_Paginator::factory($shareList);
    	$paginator->setCurrentPageNumber($this->_getParam('page'));
		$this->view->paginator = $paginator;
    }
    
    public function updateSingleItemAction() {
        $numiid=$this->getRequest()->getParam('id');
        $util=new Txy_Util_TaobaoItem();
        $util->updateTaobaoItems($numiid);
    }
    

    public function ajaxTempTaobaoStatusConfirmAction()
    {
        // action body
        include_once 'TopSdk.php';
        $this->_helper->layout()->disableLayout();
        $request=$this->getRequest();
        $status=(int)$request->getParam('statusFlag');
        $num_iid=$request->getParam('numIid');
        $item_url_spell=$request->getParam('item_url_spell');
        $item_keywords=$request->getParam('item_keywords');
        $db_tempTaobaoItems=new Application_Model_DbTable_Temptaobaoitems();
        $db_pricelist=new Application_Model_DbTable_Pricelist();
        $db_pricemark=new Application_Model_DbTable_Pricemark();
        if(0==$status){
        	$db_tempTaobaoItems->updateStatus(0, $num_iid);
        	echo "by pass success";
        	return;
        }else{
        	$db_taobaoItems=new Application_Model_DbTable_TaobaoItems();
        	if(!$db_taobaoItems->isRepeat($num_iid)){
        		echo "repeat";
        		return;
        	}
        	$c = new TopClient;
        	$c->appkey = '12532098';
        	$c->secretKey = 'c22aee3f68fe4acc9015a1e9dba1cd16';
        	$data=array();
			$dataList=array();
			$dataMark=array();
			$req_item = new TaobaokeItemsDetailGetRequest;
			$req_item->setFields("click_url,shop_click_url,title,nick,desc,price,pic_url,freight_payer,item_img");
			$req_item->setNick("淘岫玉");
			$req_item->setNumIids($num_iid);
			$resp_item = $c->execute($req_item);
			if(isset($resp_item->taobaoke_item_details->taobaoke_item_detail)){
				$itemInfo=$resp_item->taobaoke_item_details->taobaoke_item_detail;
				$data['is_taobaoke']=1;
				$data['is_onsale']=1;
				$data['num_iid']=$num_iid;
				$data['click_url']=(string)$itemInfo->click_url;
				$data['shop_click_url']=(string)$itemInfo->shop_click_url;
				$data['title']=(string)$itemInfo->item->title;
				$data['item_url_spell']=$item_url_spell;
				$data['item_keywords']=$item_keywords;
				$data['nick']=(string)$itemInfo->item->nick;
				$data['desc']=(string)$itemInfo->item->desc;
				$data['price']=(string)$itemInfo->item->price;
				$data['pic_url']=(string)$itemInfo->item->pic_url;
				$data['freight_payer']=(string)$itemInfo->item->freight_payer;
				$data['item_imgs']=$itemInfo->item->item_imgs->asXML();
				//$data['item_imgs']="aaaaaaaaaaaa";
				$req_ump = new UmpPromotionGetRequest;
				$req_ump->setItemId($num_iid);
				$resp_ump = $c->execute($req_ump);
				$ump_msg=" no ump";
				if(isset($resp_ump->promotions->promotion_in_item->promotion_in_item)){
					$umpInfo=$resp_ump->promotions->promotion_in_item->promotion_in_item;
					$data['is_promotion']=1;
					$data['promotion_name']=(string)$umpInfo->name;
					$data['promotion_price']=(string)$umpInfo->item_promo_price;
					$data['promotion_end_time']=(string)$umpInfo->end_time;
					$ump_msg=" ump success";
				}
				if(isset($resp_ump->code)&&$resp_ump->code==7){
					$data['is_promotion']=2;  //api 返回错误 ,隔断时间重新查找
					$ump_msg=" code7 api error";
				}
				$data['add_time']=new Zend_Db_Expr('now()');
				$data['update_time']=new Zend_Db_Expr('now()');
				
				$dataList['numiid']=$num_iid;
				$dataMark['numiid']=$num_iid;
				if(isset($data['promotion_price'])){
					$dataList['price']=$data['promotion_price'];
					$dataMark['min_price']=$data['promotion_price'];
					$dataMark['max_price']=$data['promotion_price'];
				}else{
					$dataList['price']=$data['price'];
					$dataMark['min_price']=$data['price'];
					$dataMark['max_price']=$data['price'];
				}
				
				$db_taobaoItems->addNewTaoBaoItems($data);
				$db_tempTaobaoItems->updateStatus(1, $num_iid);
				$db_pricelist->addNew($dataList);
				$db_pricemark->addNew($dataMark);
				echo "add success".$ump_msg;
				return;
        	}
        	echo "get empty";
    	}
    }
    
    public function ajaxItemShowlevelChangeAction(){
    	$this->_helper->layout()->disableLayout();
    	$numIid=$this->getRequest()->getParam('numIid');
    	$showLevel=$this->getRequest()->getParam('showLevel');
    	$data=array("show_level"=>$showLevel);
    	$db_taobaoItems=new Application_Model_DbTable_TaobaoItems();
    	$db_taobaoItems->updateTaobaoItems($data, $numIid);
    	echo "success";
    }
    
    public function ajaxApproveConfirmAction(){
    	include_once 'TopSdk.php';
    	$this->_helper->layout()->disableLayout();
    	$numIid=$this->getRequest()->getParam('numIid');
    	$approve=$this->getRequest()->getParam('approve');
    	$data1=array("is_approve"=>$approve);
    	$db_share=new Application_Model_DbTable_Share();
    	if(1==(int)$approve){
    		$item_url_spell=trim($this->getRequest()->getParam('item_url_spell'));
    		$item_keywords=$this->getRequest()->getParam('item_keywords');
    		$db_taobaoItems=new Application_Model_DbTable_TaobaoItems();
			$db_pricelist=new Application_Model_DbTable_Pricelist();
			$db_pricemark=new Application_Model_DbTable_Pricemark();
        	if(!$db_taobaoItems->isRepeat($numIid)){
        		echo "repeat";
        		return;
        	}
        	$c = new TopClient;
        	$c->appkey = '12532098';
        	$c->secretKey = 'c22aee3f68fe4acc9015a1e9dba1cd16';
        	$data=array();
			$dataList=array();
			$dataMark=array();
			$req_item = new TaobaokeItemsDetailGetRequest;
			$req_item->setFields("click_url,shop_click_url,title,nick,desc,price,pic_url,freight_payer,item_img");
			$req_item->setNick("淘岫玉");
			$req_item->setNumIids($numIid);
			$resp_item = $c->execute($req_item);
			if(isset($resp_item->taobaoke_item_details->taobaoke_item_detail)){
				$itemInfo=$resp_item->taobaoke_item_details->taobaoke_item_detail;
				$data['is_taobaoke']=1;
				$data['is_onsale']=1;
				$data['num_iid']=$numIid;
				$data['click_url']=(string)$itemInfo->click_url;
				$data['shop_click_url']=(string)$itemInfo->shop_click_url;
				$data['title']=(string)$itemInfo->item->title;
				$data['item_url_spell']=$item_url_spell;
				$data['item_keywords']=$item_keywords;
				$data['nick']=(string)$itemInfo->item->nick;
				$data['desc']=(string)$itemInfo->item->desc;
				$data['price']=(string)$itemInfo->item->price;
				$data['pic_url']=(string)$itemInfo->item->pic_url;
				$data['freight_payer']=(string)$itemInfo->item->freight_payer;
				$data['item_imgs']=$itemInfo->item->item_imgs->asXML();
				//$data['item_imgs']="aaaaaaaaaaaa";
				$req_ump = new UmpPromotionGetRequest;
				$req_ump->setItemId($numIid);
				$resp_ump = $c->execute($req_ump);
				$ump_msg=" no ump";
				if(isset($resp_ump->promotions->promotion_in_item->promotion_in_item)){
					$umpInfo=$resp_ump->promotions->promotion_in_item->promotion_in_item;
					$data['is_promotion']=1;
					$data['promotion_name']=(string)$umpInfo->name;
					$data['promotion_price']=(string)$umpInfo->item_promo_price;
					$data['promotion_end_time']=(string)$umpInfo->end_time;
					$ump_msg=" ump success";
				}
				if(isset($resp_ump->code)&&$resp_ump->code==7){
					$data['is_promotion']=2;  //api 返回错误 ,隔断时间重新查找
					$ump_msg=" code7 api error";
				}
				$data['add_time']=new Zend_Db_Expr('now()');
				$data['update_time']=new Zend_Db_Expr('now()');
				$dataList['numiid']=$numIid;
				$dataMark['numiid']=$numIid;
				if(isset($data['promotion_price'])){
					$dataList['price']=$data['promotion_price'];
					$dataMark['min_price']=$data['promotion_price'];
					$dataMark['max_price']=$data['promotion_price'];
				}else{
					$dataList['price']=$data['price'];
					$dataMark['min_price']=$data['price'];
					$dataMark['max_price']=$data['price'];
				}
				$db_pricelist->addNew($dataList);
				$db_pricemark->addNew($dataMark);
				
				$db_taobaoItems->addNewTaoBaoItems($data);
				//echo "add success".$ump_msg;
    		}else{
    			$req_item=new ItemGetRequest;
    			$req_item->setFields("num_iid,detail_url,title,desc,nick,price,pic_url,freight_payer,item_img");
    			$req_item->setNumIid($numIid);
    			$resp_item = $c->execute($req_item);
    			if(isset($resp_item->item)){
    				$itemInfo=$resp_item->item;
    				$data['is_taobaoke']=0;
    				$data['is_promotion']=0;
					$data['is_onsale']=1;
					$data['num_iid']=$numIid;
					$data['click_url']=(string)$itemInfo->detail_url;
					$data['shop_click_url']='0';
					$data['title']=(string)$itemInfo->title;
					$data['item_url_spell']=$item_url_spell;
					$data1['txy_url']=$item_url_spell;
					$data['item_keywords']=$item_keywords;
					$data['nick']=(string)$itemInfo->nick;
					$data['desc']=(string)$itemInfo->desc;
					$data['price']=(string)$itemInfo->price;
					$data['pic_url']=(string)$itemInfo->pic_url;
					$data['freight_payer']=(string)$itemInfo->freight_payer;
					$data['item_imgs']=$itemInfo->item_imgs->asXML();
    				$data['add_time']=new Zend_Db_Expr('now()');
					$data['update_time']=new Zend_Db_Expr('now()');
	    			$dataList['numiid']=$numIid;
					$dataMark['numiid']=$numIid;
					if(isset($data['promotion_price'])){
						$dataList['price']=$data['promotion_price'];
						$dataMark['min_price']=$data['promotion_price'];
						$dataMark['max_price']=$data['promotion_price'];
					}else{
						$dataList['price']=$data['price'];
						$dataMark['min_price']=$data['price'];
						$dataMark['max_price']=$data['price'];
					}
					$db_pricelist->addNew($dataList);
					$db_pricemark->addNew($dataMark);
    				$db_taobaoItems->addNewTaoBaoItems($data);
    				$ump_msg="no taobaoke";
    			}
    		}
    	}
    	
    	
    	$db_share->updateItem($data1, $numIid);
    	echo "success".$ump_msg;
    }
}







